package com.haust.leyou.interceptor;

import com.haust.leyou.config.JwtProperties;
import com.haust.leyou.pojo.UserInfo;
import com.haust.leyou.utils.CookieUtils;
import com.haust.leyou.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Auther: csp1999
 * @Date: 2020/12/21/15:26
 * @Description: 登录拦截器
 */
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 前置拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取 cookie 中的 token
        String token = CookieUtils.getCookieValue(request, jwtProperties.getCookieName());

        // 解析token，获取用户信息
        UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());

        // 如果userinfo 为null 则拦截
        if (userInfo == null) {
            return false;
        }

        // userinfo不为null 存入threadlocal
        THREAD_LOCAL.set(userInfo);

        // 放行
        return true;
    }

    /**
     * 后置拦截
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清空(释放)线程的局部变量，因为我们使用的是tomcat的线程池，如果不释放
        // 线程不会结束，也就不会释放线程的局部变量！
        THREAD_LOCAL.remove();
    }

    /**
     * 获取当前线程下的userinfo
     *
     * @return
     */
    public static UserInfo getUserInfo() {
        return THREAD_LOCAL.get();
    }
}
